/**
 * create by young (young2f@outlook.com) on 2020/11/9
 */

'use strict';
import React from 'react';
import IconTag from './IconTag/IconTag';
import styles from '../Index.less';

const _theme = require('../../theme');
/**
 * webpack打包，引用有问题
 */
// import {IconMap} from './utils';
import {Button, Dropdown, Empty, Menu, Divider, Tree, Tooltip} from 'antd';
import {ModalView} from 'antd-extra';
import ModalCreateNode from './modal/ModalCreateNode';
import ModalBatchCreateNode from './modal/ModalBatchCreateNode';
import ModalMoveNode from './modal/ModalMoveNode';
import ModalConfirm from './modal/ModalConfirm';

import ViewTitle from '../ViewTitle';
import ComponentBase from '../Base/ComponentBase';
import {Icon} from 'antd';

const IconFont = Icon.createFromIconfontCN({
  scriptUrl: '//at.alicdn.com/t/font_1400380_hjvm2icxm5o.js'
});
const IconMap = {
  0: <IconFont onClick={() => {
  }} type="icongongchang"/>,
  1: <IconFont type="iconbumen"/>,
  2: <IconFont type="iconzibumen"/>,
  3: <IconFont type="iconzhicheng"/>,
  4: <IconFont type="icongongxu"/>,
  5: <IconFont type="iconshebei"/>,
  6: <IconFont type="iconshebei1"/>,
  7: <IconFont type="iconbeijian"/>,
  8: <IconFont type="iconrenwu"/>,
  9: <IconFont type="iconfeiyong"/>,
  10: <IconFont type="iconjihua"/>,
  11: <IconFont type="iconguanlian"/>
};
const {TreeNode} = Tree;

class SiderTree extends ComponentBase {
  constructor(props) {
    super(props);
    this.state = {checkedKeys: []};

  }

  componentDidMount() {
    this.onLoadData().then(res => {
      this.setState(res);
    });
  }

  async onLoadData() {
    const {table, findTable, dispatch} = this.props;
    const _table = findTable ? findTable : table;

    const res = await dispatch({
      type: 'treeNode/getTree', payload: {table: _table}
    });
    if (!res) {
      this.requestReturn(null);
      return;
    }
    const res1 = await this.props.dispatch({
      type: 'treeNode/getNodes',
      payload: {table: _table}
    });
    console.log('get nodes', res1);
    if (!res1) {
      this.requestReturn(null);
      return;
    }
    const nodes = _.sortBy(res1.result, ['sort']);
    const tree = _.sortBy(res.result, ['sort']);

    return {tree, nodes};
  }

  onExpand = (_expandedKeys) => {
    const {dispatch, table} = this.props;
    let expandedKeys = typeof _expandedKeys === 'string' ? [_expandedKeys] : _expandedKeys;
    dispatch({
      type: 'treeNode/onDataLoad',
      payload: {
        table,
        expandedKeys
      }
    });
  };

  onSelect = (selectedKeys) => {
    const treeId = selectedKeys.length > 0 ? selectedKeys[0] : undefined;
    if (!treeId) return;
    this.state.treeId = treeId;
    const {nodes} = this.state;
    const node = _.find(nodes, item => item.treeId === treeId);
    this.state.treeNode = node;
    const {onSelected} = this.props;
    onSelected && onSelected(node);
  };

  getMenu = (moveDisabled, deleteDisabled, clearDisabled) => {
    return (
      <Menu onClick={this.onMenuClick}>
        <Menu.Item key="create">新建子目录</Menu.Item>
        <Menu.Item key="batchCreate">批量新建子目录</Menu.Item>
        <Menu.Item key="edit">编辑目录</Menu.Item>
        <Menu.Item disabled={moveDisabled} key="move">移动目录</Menu.Item>
        <Menu.Item disabled={deleteDisabled} key="delete">删除目录</Menu.Item>
        <Menu.Item disabled={clearDisabled} key="clear">清空目录</Menu.Item>
      </Menu>
    );
  };

  renderTreeTitle = (item, clearDisabled, deleteDisabled) => {
    const {disableEdit, disableEditTable} = this.props;
    let {title, level, name, table, treeId, editable} = item;

    disableEditTable && disableEditTable.map(item => {
      if (table === item) {
        editable = false;
      }
    });

    const label = title ? title.label : '';
    const color = title ? title.color : _theme['primary-color'];

    let style = this.state.treeId && this.state.treeId === treeId ? styles.selected : styles.notSelected;
    let isShow = treeId && this.state.treeId === treeId ? true : false;
    let editMenu = this.getMenu(false, clearDisabled, deleteDisabled);

    return (
      <div className={style}>
        {isShow && editable && !disableEdit && <Dropdown overlay={editMenu}>
          <a style={{marginLeft: '5px'}} className="ant-dropdown-link" onClick={e => e.preventDefault()}>
            <Icon type="down"/>
          </a>
        </Dropdown>}
        <IconTag className={styles.treeTitle} color={color} title={label} icon={IconMap[level]}/>
        {/*<span> <Tooltip title={treeId}>{name}</Tooltip></span>*/}

        {/*<span style={{whiteSpace: 'pre-wrap'}}>{name}</span>*/}

        <Tooltip title={name}>
          <span>{name}</span>
        </Tooltip>

      </div>
    );
  };

  renderTreeNodes = treeNodes => {
    return treeNodes && treeNodes.length ? treeNodes.map(item => {
      if (item) {
        const {treeId, children} = item;
        let clearDisabled = false;
        let deleteDisabled = false;
        if (children && children.length) {
          deleteDisabled = true;
          for (let baby of children) {
            if (baby) {
              const {children} = baby;
              if (children && children.length) {
                clearDisabled = true;
              }
            }
          }
        } else {
          clearDisabled = true;
        }
        return (
          <TreeNode
            title={this.renderTreeTitle(item, deleteDisabled, clearDisabled)}
            key={treeId}
            // icon={({ selected }) => (selected ? <FrownFilled/> : undefined)}
          >
            {item.children && this.renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
    }) : null;
  };

  createRootNode = () => {
    const {table, dispatch, onCreateRootNode, codeEdited = false} = this.props;
    const loginInfo = wStore.getStore('loginInfo');
    const {tenantCode, username} = loginInfo;
    ModalView.open(ModalCreateNode, {
      title: '新建根目录',
      width: '720px'
    }, {
      dispatch, codeEdited,
      result: node => {
        const title = {label: node['type'], color: node['backColor']};
        const type = 'treeNode/insert';
        const payload = {
          page: table,
          table,
          createUser: username,
          createUsername: this.getLoginUsername(),
          title,
          tenantCode,
          isEnabled: true, editable: true,
          name: node['name'],
          treeId: node['treeId'],
          level: 0
        };

        dispatch({type, payload}).then(res => {
          onCreateRootNode && onCreateRootNode(type, payload);
          this.requestReturn(res);
          this.componentDidMount();
        });
      }
    });
  };

  batchCreateNode = () => {
    const {table, onBatchCreateNode} = this.props;
    const {treeId, treeNode} = this.state;
    ModalView.open(ModalBatchCreateNode, {
      title: '批量新建子目录',
      width: '720px'
    }, {
      title: '批量新建子目录',
      result: node => {
        const {num} = node;
        const payload = [];
        for (let i = 0; i < num; i++) {
          const str = (i + 1).toString();
          const _title = {label: node['type'], color: node['backColor']};
          const data = {
            page: table,
            table,
            createUser: this.getLoginUser(),
            createUsername: this.getLoginUsername(),
            isEnabled: true, editable: true,
            title: _title,
            name: node['name'] + str,
            fatherId: treeId
          };
          payload.push(data);
        }
        const type = 'treeNode/insertBatch';
        const {dispatch} = this.props;
        dispatch({type, payload})
          .then(res => {
            onBatchCreateNode && onBatchCreateNode(type, payload);
            this.requestReturn(res);
            this.componentDidMount();
            this.onExpand(treeId);
          });
      }
    });
  };

  createNode = () => {
    const {table, onCreateNode, dispatch, codeEdited = false} = this.props;
    const {treeId} = this.state;
    ModalView.open(ModalCreateNode, {
      title: '新建目录',
      width: '720px'
    }, {
      dispatch, codeEdited,
      result: async node => {
        const title = {label: node['type'], color: node['backColor']};
        const type = 'treeNode/insert';
        const payload = {
          page: table,
          table,
          isEnabled: true,
          editable: true,
          title,
          name: node['name'],
          mark:node['mark'],
          fatherId: treeId,
          treeId: node['treeId'],
          sort: node['sort']
        };

        const res = await dispatch({type, payload});
        onCreateNode && onCreateNode(type, payload);
        this.requestReturn(res);
        this.componentDidMount();
        this.onExpand(treeId);
      }
    });
  };

  editNode = (treeId) => {
    const {onEditNode, codeEdited = false} = this.props;

    const {tree, nodes} = this.state;
    const value = [];
    tree && tree.length && tree.map(item => {
      value.push(item.name);
    });
    const node = _.find(nodes, item => item.treeId === treeId);
    ModalView.open(ModalCreateNode, {
      title: '编辑目录',
      width: '720px'
    }, {
      dispatch: this.props.dispatch,
      checkValue: value,
      codeEdited,
      node,
      result: node => {
        const {table} = this.props;
        const {sort, backColor} = node;
        const title = {label: node['type'], color: backColor};
        const type = 'treeNode/updateNode';
        const payload = {
          page: table,
          table, editable: true,
          title,
          name: node['name'],mark:node['mark'],
          treeId, sort
        };

        const {dispatch} = this.props;
        dispatch({type, payload}).then(res => {
          onEditNode && onEditNode(type, payload);
          this.requestReturn(res);
          this.componentDidMount();
        });
        this.onExpand(treeId);
      }
    });
  };

  deleteNode = treeId => {
    const {dispatch, table, onTreeDelete} = this.props;
    const payload = {treeId, tenantCode: this.getTenantCode(), table};
    dispatch({
      type: 'treeNode/deleteNode',
      payload
    }).then(res => {
      if (onTreeDelete) {
        onTreeDelete(treeId, res);
      }
      this.requestReturn(res);
      this.componentDidMount();
    });

  };

  moveNode = () => {
    const {table, dispatch, onMoveNode} = this.props;
    const {treeId, nodes} = this.state;
    const node = _.find(nodes, item => item.treeId === treeId);
    const _props = {dispatch, checkable: true, table, treeId, fatherId: node.fatherId};
    ModalView.open(ModalMoveNode, {
      title: '选择目录',
      width: '640px'
    }, {
      ..._props,
      result: data => {
        const {distId, isCopy} = data;
        const payload = {
          source: treeId,
          dist: distId,
          isCopy,
          table,
          tenantCode: this.getTenantCode(),
          createUser: this.getLoginUser()
        };
        let type = isCopy ? 'treeNode/copyNode' : 'treeNode/moveNode';
        dispatch({
          type,
          payload
        })
          .then(res => {
            onMoveNode && onMoveNode(type, payload);
            this.requestReturn(res);
            this.componentDidMount();
          });
      }
    });
  };

  clearNode = (treeId) => {
    const loginInfo = wStore.getStore('loginInfo');
    const {tenantCode} = loginInfo;
    const {dispatch, table} = this.props;
    const payload = {treeId, table, tenantCode};
    dispatch({
      type: 'treeNode/clear',
      payload
    })
      .then(res => {
        this.requestReturn(res);
        this.componentDidMount();
      });
  };
  setDynamicLabel = () => {

  };
  refresh = () => {
    const loginInfo = wStore.getStore('loginInfo');
    const {tenantCode} = loginInfo;
    const {dispatch, table, onLoadData} = this.props;
    const treeId = this.state.treeId;
    const payload = {treeId, table, tenantCode};
    dispatch({
      type: 'treeNode/getInfoById',
      payload
    });
    onLoadData && onLoadData(treeId);
  };

  onMenuClick = ({key}) => {
    const {treeId} = this.state;
    if (key === 'create') {
      this.createNode();
    }
    if (key === 'batchCreate') {
      this.batchCreateNode();
    }
    if (key === 'edit') {
      this.editNode(treeId);
    }
    if (key === 'move') {
      this.moveNode();
    }
    if (key === 'delete') {
      ModalView.open(ModalConfirm,
        {title: '确认', width: '320px'},
        {
          message: '确认删除目录？',
          result: confirm => {
            if (confirm) {
              this.deleteNode(treeId);
            }
          }
        }
      );
    }

    if (key === 'clear') {
      ModalView.open(ModalConfirm,
        {title: '确认', width: '320px'},
        {
          message: '确认清空目录？',
          result: confirm => {
            if (confirm) {
              this.clearNode(treeId);
            }
          }
        }
      );
    }

  };
  onCheck = node => {
    const {onCheck} = this.props;
    const {checked} = node;
    const key = checked[checked.length - 1];
    const {nodes} = this.state;
    const _node = nodes.filter(item => item.treeId === key);
    onCheck && onCheck(key, _node[0]);
    this.setState({checkedKeys: [key]});
  };
  renderTree = () => {
    const {tree, treeId} = this.state;
    const {checkable} = this.props;
    let view = tree && tree.length ?
      <div>
        {tree && tree.length && <Tree
          className={styles.customTree}
          showIcon
          onExpand={this.onExpand}
          onSelect={this.onSelect}
          defaultExpandAll={true}
          selectedKeys={[treeId]}
          autoExpandParent={false}
          checkedKeys={this.state.checkedKeys}
          checkStrictly={true}
          checkable={checkable}
          onCheck={this.onCheck}
        >
          {this.renderTreeNodes(tree)}
        </Tree>}
      </div> : <Empty style={{marginTop: 32}}/>;
    return view;

  };

  render() {
    const {title, disableEdit, selectedTreeId, subTitle, codeEdited} = this.props;

    if (selectedTreeId) {
      this.state.treeId = selectedTreeId;
      this.onSelect([selectedTreeId]);
    }
    const actions = !disableEdit ? <Button type="primary" onClick={this.createRootNode.bind(this)}
                                           className={styles.createButton}>新建根目录</Button> : undefined;
    return (<div>
        {title && <ViewTitle
          style={{background: '#fff'}}
          title={title}
          actions={actions}
          subTitle={subTitle}
        >
        </ViewTitle>}
        {this.renderTree()}
      </div>
    );
  }
}

export default SiderTree;
